<template>
  <div class="main-layout-1">
    <div style="display: flex;align-items:center;justify-content: space-between;">
      <p style="font-size: 12px;">
        <span>{{fundDetails.code}}</span>
        <span> - </span>
        <span> {{fundDetails.name}} </span>
        <span> - </span>
        <span> {{fundDetails.type}} </span>
        <span> - </span>
        <span> {{fundDetails.manager}} </span>
        <span> - </span>
        <span> {{fundDetails.fundScale}} </span>

        <span style="margin: 0 6px;">费率:</span>
        <span style="color:#ccc;text-decoration: line-through;margin-right: 4px;"> {{fundDetails.buySourceRate}} </span>
        <span>{{fundDetails.buyRate}}</span>
        <br>
        <span>收益率：</span>
        <span style="margin: 0 4px;">1天: <strong :style="{ color: fundDetails.dayGrowth > 0 ? 'red' : 'green' }">{{fundDetails.dayGrowth || '-'}}%</strong></span>
        <span style="margin: 0 4px;">1周: <strong :style="{ color: fundDetails.lastWeekGrowth > 0 ? 'red' : 'green' }">{{fundDetails.lastWeekGrowth || '-'}}%</strong></span>
        <span style="margin: 0 4px;">1月: <strong :style="{ color: fundDetails.lastMonthGrowth > 0 ? 'red' : 'green' }">{{fundDetails.lastMonthGrowth || '-'}}%</strong></span>
        <span style="margin: 0 4px;">3月: <strong :style="{ color: fundDetails.lastThreeMonthsGrowth > 0 ? 'red' : 'green' }">{{fundDetails.lastThreeMonthsGrowth || '-'}}%</strong></span>
        <span style="margin: 0 4px;">6月: <strong :style="{ color: fundDetails.lastSixMonthsGrowth > 0 ? 'red' : 'green' }">{{fundDetails.lastSixMonthsGrowth || '-'}}%</strong></span>
        <span style="margin: 0 4px;">1年: <strong :style="{ color: fundDetails.lastYearGrowth > 0 ? 'red' : 'green' }">{{fundDetails.lastYearGrowth || '-'}}%</strong></span>
      </p>
      <el-radio-group v-model="startValueIndex" @change="areaChange">
        <el-radio-button label="0" v-if="mrrq && qrjz">持有</el-radio-button>
        <el-radio-button label="7">1周</el-radio-button>
        <el-radio-button label="31">1月</el-radio-button>
        <el-radio-button label="61">2月</el-radio-button>
        <el-radio-button label="92">3月</el-radio-button>
        <el-radio-button label="183">6月</el-radio-button>
        <el-radio-button label="365">1年</el-radio-button>
        <el-radio-button label="730">2年</el-radio-button>
        <el-radio-button label="1096">3年</el-radio-button>
        <el-radio-button label="1827">5年</el-radio-button>
        <el-radio-button label="Infinity">全部</el-radio-button>
      </el-radio-group>
    </div>
    <div class="vxe-table-box-wrapper" ref="chartBoxEl"></div>
    <!--<div class="vxe-table-box-wrapper" ref="chartBoxEl2"></div>-->
  </div>
</template>

<script>
export default {
  name: 'fundDetail',
};
</script>

<script setup>
import { ref, reactive, toRaw, nextTick, watch } from 'vue';
import { useRoute } from 'vue-router'
import axios from 'axios'
import * as ECharts from 'echarts'
import { calendarData } from '/@/utils/calendar';

const { params: { fundCode }, query: { mrrq, qrjz } } = useRoute()
console.log(mrrq, qrjz)

const fundDetail = ref({})

//// 跨域无效
//axios.get(`http://fund.eastmoney.com/pingzhongdata/${fundCode}.js`).then(res => {
//  ///** * 测试数据 * @type {arry} *//*2022-01-05 08:29:49*/
//  //let ishb
//  ///*基金或股票信息*/
//  //let fS_name
//  //let fS_code
//  //let fund_sourceRate /*原费率*/
//  //let fund_Rate /*现费率*/
//  //let fund_minsg /*最小申购金额*/
//  //let stockCodes /*基金持仓股票代码*/
//  //let zqCodes /*基金持仓债券代码*/
//  //let stockCodesNew /*基金持仓股票代码(新市场号)*/
//  //let zqCodesNew /*基金持仓债券代码（新市场号）*/
//  //let syl_1n /*收益率*//*近一年收益率*/
//  //let syl_6y /*近6月收益率*/
//  //let syl_3y /*近三月收益率*/
//  //let syl_1y /*近一月收益率*/
//  //let Data_fundSharesPositions /*股票仓位测算图*/
//  //let Data_netWorthTrend /*单位净值走势 equityReturn-净值回报 unitMoney-每份派送金*/
//  //let Data_ACWorthTrend /*累计净值走势*/
//  //let Data_grandTotal /*累计收益率走势*/
//  //let Data_rateInSimilarType /*同类排名走势*/
//  //let Data_rateInSimilarPersent /*同类排名百分比*/
//  //let Data_fluctuationScale /*规模变动 mom-较上期环比*/
//  //let Data_holderStructure /*持有人结构*/
//  //let Data_assetAllocation /*资产配置*/
//  //let Data_performanceEvaluation /*业绩评价 ['选股能力', '收益率', '抗风险', '稳定性','择时能力']*/
//  //let Data_currentFundManager /*现任基金经理*/
//  //let Data_buySedemption /*申购赎回*/
//  //let swithSameType /*同类型基金涨幅榜（页面底部通栏）*/
//
//  const detail = {}
//  eval(res.data.replace(/var /g, 'detail.'))
//  console.log(detail)
//  fundDetail.value = detail
//}).catch(err => {
//  throw new Error(err)
//})

const fundDetails = ref({})
const xAxisData = []
const markAreaData = []

const startValueIndex = ref(365)
const area = localStorage.getItem('area')
if (area) {
  if (area === '0') {
    if (mrrq && qrjz) {
      startValueIndex.value = area
    }
  } else {
    startValueIndex.value = area
  }
}
const changeStartIndex = num => {
  const { totalNetWorthData = [] } = fundDetails.value
  if (totalNetWorthData.length === 0) return
  let startValue
  if (num !== '0') {
    const start = xAxisData.length - num
    startValue = start < 0 ? 0 : start
  } else {
    startValue = mrrq
  }

  $chart.setOption({
    dataZoom: {
      type: 'inside',
      startValue,
      xAxisIndex: [0, 1],
    },
  })
}

const areaChange = (newArea) => {
  changeStartIndex(newArea)
  localStorage.setItem('area', newArea)
}

const queryFundDetail = () => {
  const params = {
    code: fundCode
  }
  axios.get('https://api.doctorxiong.club/v1/fund/detail', { params }).then(res => {
    const { code, data, meta } = res.data
    fundDetails.value = data
    renderChart()
    changeStartIndex(startValueIndex.value)
  }).catch(err => err).finally(() => {

  })
}
queryFundDetail()

const chartBoxEl = ref()
let $chart
nextTick(() => {
  $chart = ECharts.init(chartBoxEl.value)
})
const renderChart = () => {
  //totalNetWorthData = [日期，单位净值，净值涨幅，每份分红]
  const { totalNetWorthData = [], netWorthData = [] } = fundDetails.value
  if (totalNetWorthData.length === 0) return

  // 生成完整x坐标轴数据
  const oneDayStamp = 1000 * 60 * 60 * 24
  const left = +new Date(totalNetWorthData[0][0])
  const right = +new Date(totalNetWorthData[totalNetWorthData.length - 1][0])
  for ( let mark = left;mark <= right;) {
    xAxisData.push(new Date(mark).toISOString().slice(0, 10))
    mark += oneDayStamp
  }

  // 生成 markArea 数据
  calendarData.list.forEach(year => {
    year.jr.forEach((item, index) => {
      const [start, end] = item
      const s = +new Date(start)
      const e = +new Date(end)
      if (e < left || s > right) return
      markAreaData.push([
        { xAxis: start, name: calendarData.label[index] },
        { xAxis: end },
      ])
    })
  })

  const gridRight = 2 // %
  const option = {
    color: ['rgb(255,164,164)', 'rgba(255, 0, 0, 1)'],
    grid: [
      {
        left: 40,
        right: `${gridRight}%`,
        top: '4%',
        //height: '48%',
        bottom: '3%',
        //show: true,
        borderColor: 'red',
      },
      {
        left: 40,
        right: `${gridRight}%`,
        top: '100%',
        //height: '48%',
        bottom: 0,
        //show: true,
        borderColor: 'red',
      },
    ],
    //dataZoom: [
    //  {
    //    type: 'inside',
    //    startValue: mrrq,
    //    xAxisIndex: [0, 1],
    //  }
    //],
    axisPointer: {
      link: [
        {
          xAxisIndex: 'all',
        }
      ],
    },
    dataset: [
      {
        dimensions: ['日期', '累计净值'],
        source: totalNetWorthData,
      },
      {
        dimensions: ['日期', '单位净值'],
        source: netWorthData,
      }
    ],
    legend: {
      data: ['累计净值', '单位净值'],
    },
    tooltip: {
      renderMode: 'richText',
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
      transitionDuration: 0,
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData,
        axisLabel: {
          fontSize: 10,
        },
        axisLine: {
          // onZero: false,
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      {
        gridIndex: 1,
        type: 'category',
        data: xAxisData,
        axisLabel: {
          fontSize: 10,
        },
        axisLine: {
          //onZero: false,
        },
        axisTick: {
          alignWithLabel: true,
        },
        //position: 'top',
      }
    ],
    yAxis: [
      {
        type: 'value',
        scale: true,
        axisLabel: {
        },
        axisLine: {
        },
      },
      {
        gridIndex: 1,
        type: 'value',
        scale: true,
        axisLabel: {
        },
        axisLine: {
        },
        inverse: true,
      },
    ],
    series: [
      {
        type: 'line',
        datasetIndex: 0,
        showSymbol: false,
        connectNulls: false,
        lineStyle: {
          width: 1,
        },
        markLine: {
          lineStyle: {
            color: 'red',
            width: 1,
          },
          label: {
            color: 'red',
            position: 'insideMiddleBottom',
          },
          emphasis:{
            lineStyle: {
              width: 1,
            },
          },
          data: [
            //{
            //  yAxis: qrjz,
            //},
            [
              {
                name: qrjz,
                yAxis: qrjz,
                xAxis: mrrq,
                symbolSize: 5,
              },
              {
                yAxis: qrjz,
                x: `${100-gridRight}%`,
                symbol: 'none',
              }
            ],
          ],
        },
        markArea: {
          silent: true,
          label: {
            fontSize: 10,
            color: 'red',
            position: 'insideTop',
          },
          itemStyle: {
            color: 'rgba(255, 0, 0, 0.1)',
            borderColor: 'rgba(255, 0, 0, 0.1)',
            borderWidth: 1,
            borderType: 'dashed',
          },
          data: markAreaData,
        },
        emphasis: {
          lineStyle: {
            width: 1,
          },
        },
      },
      {
        type: 'line',
        datasetIndex: 1,
        //xAxisIndex: 1,
        //yAxisIndex: 1,
        showSymbol: false,
        connectNulls: false,
        lineStyle: {
          width: 1,
        },
        emphasis: {
          lineStyle: {
            width: 1,
          },
        },
      },
    ]
  };

  $chart.setOption(option)
}

</script>

<style scoped lang='scss'>

</style>
